﻿

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace AutoTool
{
    public static class RepositoryGenerator
    {
        public static void GenerateRepository(string tableName, List<string> columns, string primaryKey)
        {
            // 当前运行路径（例如 bin\Debug\netcoreapp3.1\）
            string currentPath = AppDomain.CurrentDomain.BaseDirectory;

            // 从当前路径退回到 news-sys 的根目录
            string projectRootPath = Path.Combine(currentPath, "..\\..\\..\\..");

            // 拼接目标路径 NewsEntity\ADO.NETHelper\
            string targetPath = Path.Combine(projectRootPath, "ADO.NETDatabaseModule", "ADO.NETHelper");

            // 转换为标准绝对路径
            targetPath = Path.GetFullPath(targetPath);
            var className = $"{tableName}Repository";
            var interfaceName = $"I{className}";
            var filePath = @$"{targetPath}\{className}.cs";
            var interfaceFilePath = @$"{targetPath}\{interfaceName}.cs";

            var columnsList = string.Join(", ", columns);
            var parameterPlaceholders = string.Join(", ", columns.Select(c => "@" + c));

            // 生成仓储接口代码
            var interfaceCode = $@"
using NewsEntity.Models;
using System;
using System.Collections.Generic;

namespace ADO.NETDatabaseModule.ADO.NETHelper
{{
    public interface {interfaceName}
    {{
        List<{tableName}> GetAll{tableName}();
        List<{tableName}> Get{tableName}ByPrimaryKey(Guid id);
        {tableName} Get{tableName}ById(Guid id);
        void Insert{tableName}({tableName} entity);
        void Delete{tableName}(Guid id);
        void Update{tableName}({tableName} entity);
    }}
}}";

            // 生成仓储实现代码
            var repositoryCode = $@"
using NewsEntity.Models;
using System;
using System.Collections.Generic;
using System.Data;

namespace ADO.NETDatabaseModule.ADO.NETHelper
{{
    public class {className} : {interfaceName}
    {{
        public readonly DatabaseHelper _dbHelper;

        public {className}()
        {{
            _dbHelper = new DatabaseHelper();
        }}

        public List<{tableName}> GetAll{tableName}()
        {{
            string query = ""SELECT * FROM {tableName}"";
            DataTable result = _dbHelper.ExecuteQuery(query);
            return DataMapper.MapToList<{tableName}>(result);
        }}

        public List<{tableName}> Get{tableName}ByPrimaryKey(Guid id)
        {{
            string query = ""SELECT * FROM {tableName} WHERE {primaryKey} = @{primaryKey}"";
            var parameters = new Dictionary<string, object>
            {{
                {{ ""@{primaryKey}"", id }}
            }};

            DataTable result = _dbHelper.ExecuteQuery(query, parameters);
            return DataMapper.MapToList<{tableName}>(result);
        }}

        public {tableName} Get{tableName}ById(Guid id)
        {{
            string query = ""SELECT * FROM {tableName} WHERE {primaryKey} = @{primaryKey}"";
            var parameters = new Dictionary<string, object>
            {{
                {{ ""@{primaryKey}"", id }}
            }};

            DataTable result = _dbHelper.ExecuteQuery(query, parameters);
            if (result.Rows.Count > 0)
            {{
                return DataMapper.MapToObject<{tableName}>(result.Rows[0]);
            }}
            return null;
        }}

        public void Insert{tableName}({tableName} entity)
        {{
            string query = ""INSERT INTO {tableName} ({columnsList}) VALUES ({parameterPlaceholders})"";
            var parameters = new Dictionary<string, object>
            {{
                {string.Join($",{Environment.NewLine}                ", columns.Select(c => $"{{ \"@{c}\", entity.{c} }}"))}
            }};

            _dbHelper.ExecuteNonQuery(query, parameters);
        }}

        public void Delete{tableName}(Guid id)
        {{
            string query = ""DELETE FROM {tableName} WHERE {primaryKey} = @{primaryKey}"";
            var parameters = new Dictionary<string, object>
            {{
                {{ ""@{primaryKey}"", id }}
            }};

            _dbHelper.ExecuteNonQuery(query, parameters);
        }}

        public void Update{tableName}({tableName} entity)
        {{
            string query = ""UPDATE {tableName} SET {string.Join(", ", columns.Select(c => $"{c} = @{c}"))} WHERE {primaryKey} = @{primaryKey}"";
            var parameters = new Dictionary<string, object>
            {{
                {string.Join($",{Environment.NewLine}                ", columns.Select(c => $"{{ \"@{c}\", entity.{c} }}"))},
                {{ ""@{primaryKey}"", entity.{primaryKey} }}
            }};

            _dbHelper.ExecuteNonQuery(query, parameters);
        }}
    }}
}}";

            // 写入接口代码文件
            File.WriteAllText(interfaceFilePath, interfaceCode);
            // 写入仓储实现代码文件
            File.WriteAllText(filePath, repositoryCode);
        }
    }
}
